<template>
<div>
  <h1 style="text-align: center">注册</h1>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="ruleForm.password"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmpassword">
      <el-input type="password" v-model="ruleForm.confirmpassword"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即注册</el-button>
      <router-link :to="{name: 'Login'}">
        <el-button style="margin: 0px 10px">
          去登录
        </el-button>
      </router-link>
    </el-form-item>
  </el-form>
</div>
</template>

<script>



export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致！"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: '',
        password: '',
        confirmpassword: '',
        email: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          {
            pattern: /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){6,20}$/,
            message: "6-20位英文字母、数字或者符号（除空格），且字母、数字和标点符号至少包含两种",
            trigger: "blur"
          }
        ],
        confirmpassword: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
            message: "请输入正确的邮箱",
            trigger: "blur"
          }

        ]

      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this
          console.log(this.ruleForm);
          this.$axios.post('/user/save', this.ruleForm).then(res => {
            console.log(res)
            _this.$alert('注册成功', '提示', {
              confirmButtonText: '确定',
              //调回列表页
              callback: action => {
                _this.$router.push("/login")
              }
            });
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

  }
}

</script>

<style scoped>

</style>